package com.pointcircle.core.web.auth;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.pointcircle.core.ApplicationContextHolder;
import com.pointcircle.core.entity.User;
import com.pointcircle.core.repository.UserRepository;
import com.pointcircle.core.service.PropertyService;
import com.pointcircle.core.util.JwtUtils;

public class JwtRealm extends AuthorizingRealm {
	
	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof JwtToken;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		User user = (User) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		UserRepository userRepository = ApplicationContextHolder.getBean(UserRepository.class);
		List<String> roles = userRepository.findRolesById(user.getId());
		info.setRoles(new HashSet<String>(roles));
		Set<String> permissions = userRepository.findApiPermissionsById(user.getId());
		info.addStringPermissions(permissions);
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		PropertyService propertyService = ApplicationContextHolder.getBean(PropertyService.class);
		String jwtToken = (String) token.getCredentials();
		if(StringUtils.isEmpty(jwtToken)) {
			throw new AuthenticationException(
				propertyService.getProperty("pointcircle.framework.message.auth.token-invalid")
			);
		}
		String userId = JwtUtils.getUserId(jwtToken);
		if(StringUtils.isEmpty(userId)) {
			throw new AuthenticationException(
				propertyService.getProperty("pointcircle.framework.message.auth.token-invalid")
			);
		}
		UserRepository userRepository = ApplicationContextHolder.getBean(UserRepository.class);
		User user = userRepository.findOne(userId);
		if(user == null) {
			throw new AuthenticationException(
				propertyService.getProperty("pointcircle.framework.message.auth.user-not-exist")
			);
		}
		if(!JwtUtils.verify(jwtToken, userId, user.getPasswordHex())) {
			throw new AuthenticationException(
				propertyService.getProperty("pointcircle.framework.message.auth.token-invalid")
			);
		}
		return new SimpleAuthenticationInfo(user, jwtToken, getName());
	}
	
}
